package router

import (
	"gin-web/app/api"
	"gin-web/app/middleware"
	"github.com/gin-gonic/gin"
	"github.com/ngaut/log"
	"time"
)

func InitRouter() *gin.Engine {
	r := gin.Default()
	r.Use(LoggerToFile())
	authMiddleware := middleware.JwtMiddleware
	r.POST("/api/login", authMiddleware.LoginHandler)

	v1 := r.Group("/api")
	v1.Use(authMiddleware.MiddlewareFunc())
	v1.Use(middleware.CheckCasbinAllow)
	{
		v1.GET("/user", api.User.User)
		v1.GET("/hello", nil)
	}

	return r
}

func LoggerToFile() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()

		// 处理请求
		c.Next()

		// 结束时间
		endTime := time.Now()

		// 执行时间
		latencyTime := endTime.Sub(startTime)

		// 请求方式
		reqMethod := c.Request.Method

		// 请求路由
		reqUri := c.Request.RequestURI

		// 状态码
		statusCode := c.Writer.Status()

		// 请求IP
		clientIP := c.ClientIP()

		// 日志格式
		log.Infof("status_code:%d,latency_time:%d,client_ip:%s,req_method:%s,req_uri:%s ", statusCode, latencyTime, clientIP, reqMethod, reqUri)
	}
}
